<?php

namespace Modules\Production\Repository;

use App\Services\InventoryService;
use App\Services\UnitService;
use Illuminate\Support\Facades\DB;
use Modules\Base\Repository\MaterialRepository;
use Modules\Production\Models\DassemblyOrder;
use Modules\Production\Models\DassemblyOrderDetail;
use App\Enums\InvTransDocType;
use Modules\Production\Models\DassemblyOrderProduct;

class DassemblyOrderRepository
{

    /**
     * 保存数据信息
     * @param $postData
     * @return bool
     * @throws \Exception
     */
    static public function storeBy($postData){

        $order = [
            'docno' => $postData['fbillno'],
            'fid' => $postData['fid'],
            'order_type' => $postData['faffairtype'],
            'org_code' => $postData['fdatefstockorgid_number'],
            'org_name' => $postData['fdatefstockorgid_name']
        ];

        try {
            DB::beginTransaction();
            $orderId = (new DassemblyOrder)->storeBy($order);
            $orderItem = [];
            foreach ($postData['FEntry'] as $item){

                //print_r($item);exit();

                $material = MaterialRepository::getMaterialByFid($item['fmaterialid']);
                if(!$material){
                    throw new \Exception("成品编码[{$item['fmaterial_number']}]对应内码[{$item['fmaterialid']}]不存在");
                }

                $orderProductId = DassemblyOrderProduct::insertGetId([
                    'order_id'      => $orderId,
                    'fseq'          => $item['fseq'],
                    'cargo_code'    => $item['fownerid_number'],
                    'cargo_name'    => $item['fownerid_name'],
                    'fentry_id'     => $item['fentryid'],
                    'material_id'   => $material['id'],
                    'qty'           => $item['fqty'],
                    'wms_code'      => $item['fstockid_number'],
                    'creator_id'    => UnitService::getUserId(),
                    'created_at'    => time()
                ]);

                foreach ($item['FSubEntity'] as $sonItem){

                    $material = MaterialRepository::getMaterialByFid($sonItem['fmaterialidsetyid']);
                    if(!$material){
                        throw new \Exception("子件编码[{$sonItem['fmaterialidsety_number']}]对应内码[{$sonItem['fmaterialidsetyid']}]不存在");
                    }
                    $orderItem[] = [
                        'order_id' => $orderId,
                        'product_id' => $orderProductId,
                        'fseq' => $sonItem['fseqsety'],
                        'fentry_id' => $sonItem['fdetailid'],
                        'material_id' => $material['id'],
                        'qty' => $sonItem['fqtysety'],
                        'wms_code' => $sonItem['fstockidsety_number'],
                        'creator_id' => UnitService::getUserId(),
                        'created_at' => time()
                    ];

                }
            }

            DassemblyOrderDetail::insert($orderItem);

            DB::commit();
            return true;

        }catch (\Exception $e){
            DB::rollBack();
            throw $e;
        }

    }

    /**
     * 组装拆卸单据头列表
     * @param $params
     * @return mixed
     */
    static public function getList($params){

        $builder = self::getWhere($params);

        $limit = isset($params['limit']) ? $params['limit'] : 100;

        return $builder->orderBy('id','desc')->with(['material'])->paginate($limit);

    }

    /**
     * 列表筛选条件拼接
     * @param $params
     * @return DassemblyOrder
     */
    static public function getWhere($params){

        $builder = new DassemblyOrder();

        $canQueryField = $builder->getFields();
        foreach($params as $key => $val){
            if(!in_array($key,$canQueryField) || $val == ''){
                continue;
            }

            if($key == 'status'){
                $builder = $builder->whereIn($key,explode(',',$val));
            }else{
                $builder = $builder->where($key,$val);
            }

        }

        return $builder;

    }

    /**
     * 查询一条组装拆卸单据头信息
     * @param $id
     * @return mixed
     */
    static public function getOrderOneById($id){
        return DassemblyOrder::find($id);
    }


    /**
     * 拆卸明细入库
     */
    static public function DassemblyIn($id,$postData){


    }

}
